package com.voxel.sense.infomsg.module.firm;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.view.EmptyView;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.ConditionBean;
import com.voxel.sense.infomsg.interfaces.listener.OnDropMenuButtonListener;
import com.voxel.sense.infomsg.interfaces.listener.onClickSubmitListener;
import com.voxel.sense.infomsg.module.common.dropmenu.DropPickMenuBuilder;
import com.voxel.sense.infomsg.module.common.dropmenu.DropPickMenuManager;
import com.voxel.sense.infomsg.module.firm.details.FirmInfoDetailActivity;
import com.voxel.sense.infomsg.module.firm.search.SearchFirmActivity;
import com.voxel.sense.infomsg.view.decoration.LinearItemDecoration;
import com.voxel.sense.infomsg.view.dropmenu.DropDownMenu;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.model.api.response.FirmListEntity;

/**
 * Created by chenyiyao on 2017/11/1.
 */

public class FirmListInfoActivity extends BViewActivity<FirmListInfoContract.Presenter> implements
        FirmListInfoContract.View, onClickSubmitListener, OnDropMenuButtonListener {
    @BindView(R.id.drop_down_menu)
    DropDownMenu drop_down_menu;
    @BindView(R.id.btn_search_left)
    ImageView btn_search_left;
    @BindView(R.id.tv_search)
    TextView tv_search;

    private RecyclerView recycle_view; //公司列表
    private SmartRefreshLayout refresh_layout;//下拉刷新头
    private EmptyView empty_view;//占位的空界面布局
    private RecyclerAdapter mFirmListAdapter;//公司列表适配器
    //-----------------------------------

    private boolean isFirstEnter = true;//是否首次进入
    private DropPickMenuManager mMenuManager;//下拉菜单管理类

    public static void show(Context context, String currentCity) {
        Intent intent = new Intent(context, FirmListInfoActivity.class);
        intent.putExtra(Constants.CURRENT_CITY, currentCity);
        context.startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_firm_list_info;
    }

    @Override
    protected FirmListInfoContract.Presenter initPresenter() {
        return new FirmListInfoPresenter(this);
    }


    @Override
    protected boolean initArgs(Bundle bundle) {
        return super.initArgs(bundle);
    }

    @Override
    protected void initData() {
        super.initData();
        //初始化返回按钮
        tv_search.setText(getString(R.string.title_search_hint_firm));
        initContentView();
        initAdapter();
        if (isFirstEnter) {
            refresh_layout.autoRefresh();//第一次进入触发自动刷新，演示效果
        }
    }

    @Override
    protected void initEven() {
        super.initEven();
        //滑动监听
        refresh_layout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                if (NetworkUtils.isConnected()) {
                    mPresenter.doLoadMoreData();
                } else {
                    showEmptyView(getString(R.string.network_unavailable), true);
                    refresh_layout.finishLoadMore();
                }
            }
        });

        //下拉刷新控件监听
        refresh_layout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                if (NetworkUtils.isConnected()) {
                    //重新刷新，需要改变状态，可以加载更多数据
                    refresh_layout.setNoMoreData(false);
                    mPresenter.doLoadData();
                } else {
                    refresh_layout.finishRefresh();
                    showEmptyView(getString(R.string.network_unavailable), true);
                }
            }
        });

        empty_view.addRefreshBtnEvent(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                empty_view.triggerOk();
                boolean b = refresh_layout.autoRefresh();
                //刷新过于频繁会导致失败，不会回调刷新方法
                if (!b) {
                    showEmptyView("", true);
                }
            }
        });
    }


    private void initAdapter() {
        mFirmListAdapter = new FirmListInfoAdapter(new RecyclerAdapter.AdapterListener<FirmListEntity>() {

            @Override
            public void onItemClick(RecyclerAdapter.ViewHolder holder, FirmListEntity bean) {
                String companyId = bean.getCompanyId();
                FirmInfoDetailActivity.show(FirmListInfoActivity.this, bean, companyId);
            }

            @Override
            public void onItemLongClick(RecyclerAdapter.ViewHolder holder, FirmListEntity companyDataBean) {

            }
        });
        recycle_view.setLayoutManager(new LinearLayoutManager(this));
        //设置下划线
        LinearItemDecoration linearItemDecoration = new LinearItemDecoration(R.drawable.recycle_divider_10dp);
        linearItemDecoration.setDrawFirstItem(true).
                setDrawVerticalModelLeftAndRightBorder(true,true);
        recycle_view.addItemDecoration(linearItemDecoration);
        recycle_view.setAdapter(mFirmListAdapter);
    }

    /**
     * 创建菜单View和公司列表的View
     */
    private void initContentView() {
        onCreatListContent();
    }

    /**
     * 构造公司列表内容View
     */
    private void onCreatListContent() {
        //初始化公司列表控件
        View view = LayoutInflater.from(this).inflate(R.layout.layout_recycler_emptty, null);
        refresh_layout = view.findViewById(R.id.refresh_layout);
        recycle_view = view.findViewById(R.id.recycle_view);
        empty_view = view.findViewById(R.id.empty_view);
        empty_view.bind(refresh_layout);

        //设置是否可用上拉加载更多，首次刷新不允许底部加载更多
        refresh_layout.setEnableHeaderTranslationContent(false);
        //数据不满一页时，不能加载更多
        refresh_layout.setEnableLoadMoreWhenContentNotFull(true);
        //初始化筛选栏管理工具
        DropPickMenuBuilder menuBuilder = new DropPickMenuBuilder(drop_down_menu, view);
        //创建列表
        mMenuManager = menuBuilder.buildIndustryList()
                .buildSuperviseList()
//                .buildSmartList()
                .addResetAndSubmitListener(this)
                .addItemOnclickListener(MenuListItemListener)
                .build();
        mPresenter.doLoadFilterMenuData();
    }


    /**
     * 菜单列表item点击监听
     */
    @SuppressWarnings("unchecked")
    RecyclerAdapter.AdapterListenerImpl MenuListItemListener = new RecyclerAdapter.AdapterListenerImpl<ConditionBean>() {
        @Override
        public void onItemClick(RecyclerAdapter.ViewHolder holder, ConditionBean bean) {
            super.onItemClick(holder, bean);
            switch (bean.getType()) {
                case Constants.TYPE_AREA://地区
                    if (bean.isSelect()) {
                        mPresenter.putSearTarget(bean.getType(), bean.getDesc());
                    } else {
                        mPresenter.removeSearchData(bean.getType(), bean.getDesc());
                    }
                    break;
                case Constants.TYPE_IDUSTRY://行业类型
                case Constants.TYPE_NATURE://监管
                case Constants.TYPE_LEVEL:
                case Constants.TYPE_SMART_SORT:
                    if (bean.isSelect()) {
                        mPresenter.putSearTarget(bean.getType(), bean.getTipCode());
                    } else {
                        mPresenter.removeSearchData(bean.getType(), bean.getTipCode());
                    }
                    break;
            }
        }
    };

    @OnClick({R.id.btn_search_left, R.id.tv_search})
    void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_search_left:
                onBackPressed();
                break;
            case R.id.tv_search:
                SearchFirmActivity.show(this);
                break;
        }
    }

    //列表提交按钮
    @Override
    public void onSubmit(List list, String type) {
        //若占位布局显示了，会遮挡住下拉控件，需先隐藏占位空布局
        empty_view.triggerOk();
        refresh_layout.autoRefresh();
//        mPresenter.doLoadData();
        drop_down_menu.closeMenu();
    }

    @Override
    public RecyclerAdapter<FirmListEntity> getRecyclerViewAdapter() {
        return mFirmListAdapter;
    }

    @Override
    public void onAdapterDataChanged() {
        empty_view.triggerOkOrEmpty(mFirmListAdapter.getItemCount() > 0 ? true : false);

    }

    @Override
    public void onShowNoMore(boolean b) {
        refresh_layout.setNoMoreData(true);
    }

    @Override
    public void onRefreshFinish() {
        if (isFirstEnter) {
            isFirstEnter = false;
        }
        refresh_layout.finishRefresh();
        empty_view.triggerOkOrEmpty(mFirmListAdapter.getItemCount() > 0 ? true : false);
    }

    @Override
    public void onLoadMoreFinish() {
        refresh_layout.finishLoadMore();
    }

    @Override
    public void showEmptyView(String desc, boolean btnVisible) {
        boolean b = mFirmListAdapter.getItemCount() > 0;
        if (!b && !TextUtils.isEmpty(desc)) {
            empty_view.triggerError(desc);
        } else if (b) {
            //发生错误，列表有数据，不能显示空界面
            super.showError(desc);
        } else if (!NetworkUtils.isConnected()) {
            empty_view.triggerNetError();
        } else {
            empty_view.triggerEmpty();
        }
    }


    @Override
    public void onRefreshSmartMenuUI(List<ConditionBean> list) {
        mMenuManager.setFirmSmartSortData(list);
    }

    @Override
    public void onRefreshIdustryMenuData(List<ConditionBean> list) {
        mMenuManager.setIdustryData(list);
    }

    @Override
    public void onRefreshSuperviseMenuData(List<ConditionBean> natureList, List<ConditionBean> LevelList) {
        mMenuManager.setSuperviseNatureData(natureList);
        mMenuManager.setSuperviseLevelData(LevelList);
    }

    @Override
    public void onResetClick(String type) {
        mPresenter.doCleanCondition(type);
    }

    @Override
    public void onSubmitClick(String type) {
        //若占位布局显示了，会遮挡住下拉控件，需先隐藏占位空布局
        empty_view.triggerOk();
        refresh_layout.autoRefresh();
//        mPresenter.doLoadData();
        drop_down_menu.closeMenu();
    }
}
